<template>
  <div>
    <ListTab v-model="handleStatus" :tabs="tabList" :show-header="!showMobilePage" is-table @tabClick="handleTabClick" />
    <div :class="{'mobile-table mobile-min-height':showMobilePage}" class="operator-manage min-fill-page">
      <div class="table-list">
        <div v-if="!showMobilePage" class="filter">
          <FilterInput
            ref="FilterToolRef"
            v-model="paramsObj"
            :filter-list="filterList"
            show-search-btn
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"
            @filterTagStatus="filterTagStatus" />
        </div>
        <div class="list-top">
          <Title :title="'角色列表'" :is-show="true" :total="list.total" :style="{margin: showMobilePage?'0 0 12px 12px':'24px 0 12px 0'}" style="flex: 1"/>
          <div v-if="!showMobilePage && (hasRouteAuth(['auth:operator:edit', 'auth:operator:adminEdit']))" class="btn-right">
            <el-button type="primary" size="small" @click="onMergeClick">合并角色</el-button>
            <create-button :icon="'el-icon-plus'" class="btn" add-name="添加新角色" create-link-name="createRole"/>
          </div>
        </div>
        <div v-loading="listLoading" style="min-height: 300px;">
          <u-table
            v-if="list && list.items && list.items.length > 0"
            ref="multipleTable"
            :data="list.items"
            :border="true"
            :height="setTableHeight"
            :row-height="rowHeight()"
            :row-class-name="tableRowClassName"
            beautify-table
            header-drag-style
            element-loading-text="加载中..."
            empty-text="暂无数据"
            class="fb-table"
            header-cell-class-name="order-data-header-cell"
            fit
            hightlight-current-row
            @select="selectTable"
            @select-all="selectTable">
            <u-table-column
              :selectable="selectable"
              type="selection"
              align="center"
              width="55"/>
            <u-table-column prop="roleName" align="left" min-width="120" label="角色名称" sortable>
              <template slot-scope="scope">
                <ToolTip :content="scope.row.roleName" />
              </template>
            </u-table-column>
            <u-table-column prop="operatorNum" align="left" min-width="120" label="操作员数量" sortable>
              <template slot-scope="scope">
                <div class="link-num" @click="searchOpeartor(scope.row)">{{ scope.row.operatorNum }}</div>
              </template>
            </u-table-column>
            <u-table-column prop="status" align="left" min-width="120" label="状态" sortable>
              <template slot-scope="scope">
                <span :class="!scope.row.status ? 'user-status-forbidden' : 'user-status-normal'">
                  {{ scope.row.status === 1?'启用':'禁用' }}
                </span>
              </template>
            </u-table-column>
            <u-table-column align="left" label="操作">
              <template slot-scope="scope">
                <div v-if="!showMobilePage" style="display:flex;">
                  <div v-if="!isEditDisabled(scope.row.roleId)" class="button-text" @click="toEdit(scope.row)">编辑</div>
                  <div v-else class="button-text" @click="toEdit(scope.row)">查看</div>
                  <div v-if="hasRouteAuth(['auth:operator:edit', 'auth:operator:adminEdit'])" class="button-text bl" @click="toEdit(scope.row, true)">复制</div>
                </div>
                <tableOperateBtn v-else>
                  <el-dropdown-item v-if="!isEditDisabled(scope.row.roleId)" style="width:90px;text-align: center" @click.native="toEdit(scope.row)">
                    <div>编辑</div>
                  </el-dropdown-item>
                  <el-dropdown-item v-else style="width:90px;text-align: center" @click.native="toEdit(scope.row)">
                    <div>查看</div>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="hasRouteAuth(['auth:operator:edit', 'auth:operator:adminEdit'])" style="width:90px;text-align: center" @click.native="toEdit(scope.row, true)">
                    <div>复制</div>
                  </el-dropdown-item>
                </tableOperateBtn>
              </template>
            </u-table-column>
          </u-table>
          <empty-placeholder v-else-if="!isInit" style="margin-bottom: 24px" />
          <el-row v-if="showMobilePage" type="flex" justify="left">
            <el-pagination
              v-show="list.total > 0"
              :current-page="list.page"
              :page-size="list.perPage"
              :total="list.total"
              :small="true"
              :page-sizes="[20, 50, 100, 250, 500]"
              :layout="pageLayout"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-row>
        </div>
        <fixed-pagination v-if="list.total > 0 && !showMobilePage || showMobilePage">
          <template v-if="showMobilePage">
            <div style="margin-left: 0">
              <el-dropdown v-if="showMobilePage" trigger="click">
                <el-button size="small" class="more-actions" style="margin: 0 24px 0 6px" >
                  操作<i v-if="!showMobilePage" class="el-icon-caret-top"/>
                </el-button>
                <el-dropdown-menu slot="dropdown" style="padding: 0;">
                  <el-dropdown-item style="text-align: center" @click.native="changeStatus(1)">
                    <div>启用</div>
                  </el-dropdown-item>
                  <el-dropdown-item style="text-align: center" @click.native="changeStatus(0)">
                    <div>禁用</div>
                  </el-dropdown-item>
                  <el-dropdown-item style="text-align: center" @click.native="onMergeClick">
                    <div>合并角色</div>
                  </el-dropdown-item>
                  <el-dropdown-item style="text-align: center" @click.native="deleteItem">
                    <div style="color: red">删除</div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
            <FilterInput
              ref="FilterToolRef"
              v-model="paramsObj"
              :filter-list="filterList"
              show-mobile-icon
              show-search-btn
              @handelClick="queryClick"
              @queryEmpty="queryEmpty"
              @filterTagStatus="filterTagStatus" />
            <CreateBtn
              v-if="hasRouteAuth(['auth:operator:edit', 'auth:operator:adminEdit'])"
              mobile-table
              style="width: 100%"
              text="添加新角色"
              @click.native="toCreate"
            />
          </template>
          <template v-else>
            <div class="more-btn-group">
              <MoreOpeator
                :list="[
                  {label: '启用', handelClick: moreOperateChangeStatus(1)},
                  {label: '禁用', handelClick: moreOperateChangeStatus(0)},
                  {label: '删除', handelClick: deleteItem}
                ]"
                label="批量操作"
                style="margin-right:14px;"
              />
              <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
            </div>
            <el-pagination
              v-show="list.total > 0"
              :current-page="list.page"
              :page-size="list.perPage"
              :total="list.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              layout="total, prev, pager, next, sizes, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </template>
        </fixed-pagination>
      </div>
    </div>
    <RolesMergeDialog
      ref="rolesMergeDialogRef"
      :loading="mergeLoading"
      :role-list="multipleSelectionAll"
      @handleRolesMerge="handleRolesMerge" />
  </div>
</template>

<script>
import { hasRouteAuth, ROUTER_TYPES } from '@/utils/permission';
import { roleList, deleteRole, changeRoleStatus, mergeRoles } from '@/api/auth';
import CreateButton from '@/components/CreateButton';
import CreateBtn from '@/components/Common/baseComponent/createBtn';
import Title from '@/components/Title';
import ListTab from '@/components/ListTab';
import RolesMergeDialog from './components/rolesMergeDialog';
import { mapState } from 'vuex';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import { allAuth } from '@/components/AuthPage/authData';

export default {
  components: { CreateButton, CreateBtn, Title, EmptyPlaceholder, ListTab, RolesMergeDialog },
  mixins: [tableSelections, TableAdaptive, mobileTable],
  data() {
    return {
      list: '',
      listLoading: false,
      mergeLoading: false,
      isInit: true,
      perPage: 20,
      page: 1,
      handleStatus: 0,
      screenWidth: document.body.clientWidth,
      isUmyTable: true,
      idKey: 'roleId', // 多选框参数
      tableRefName: 'multipleTable',
      paramsObj: {
        authName: '',
        roleName: ''
      },
      allAuth
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    tabList() {
      return [
        { id: 0, name: '角色管理', isHidden: hasRouteAuth(ROUTER_TYPES.AUTH_ROLE) },
        { id: 1, name: '操作员管理', isHidden: hasRouteAuth(ROUTER_TYPES.AUTH_OPERATOR) }
      ];
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 224 : 220;
    },
    filterList() {
      const arr = [
        { keyword: 'roleName', name: '角色名称', labelWidth: '70px', type: 'input' },
        { keyword: 'authName', name: '权限名称', type: 'cascaderSelectWithChild', labelName: 'label', valueName: 'id',
          multiple: false, checkStrictly: false, showAllLevels: true, childrenVal: 'children', options: this.allAuth },
        { keyword: 'status', name: '状态', type: 'select', options: [{ value: 1, label: '启用' }, { value: 0, label: '禁用' }] }
      ];
      return arr;
    }
  },
  watch: {
    list: {
      handler: function(data) {
        this.$nextTick(() => {
          if (this.setSelectRow) {
            this.setSelectRow(data.items);
          }
        });
      },
      deep: true
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'authEditRole') {
      to.meta.isChange = true;
    } else {
      to.meta.isChange = false;
    }
    if (hasRouteAuth([ROUTER_TYPES.AUTH_ROLE])) {
      next();
    } else if (hasRouteAuth([ROUTER_TYPES.AUTH_OPERATOR])) {
      next('/user/operator');
    } else if (hasRouteAuth([ROUTER_TYPES.AUTH_LOG])) {
      next('/user/log');
    } else {
      next('/');
    }
  },
  activated() {
    this.handleStatus = 0;
    if (!this.$route.meta.isChange) {
      this.getList(true);
    } else {
      if (this.list && this.list.items && this.list.items.length === 0) {
        this.getList(true);
      } else {
        this.getList();
      }
    }
  },
  methods: {
    hasRouteAuth,
    handleTabClick(id) {
      id === 1 && this.$router.push({
        name: 'operatorManage'
      });
    },
    toCreate() {
      this.$router.push({ name: 'createRole' });
    },
    onMergeClick() {
      if (this.multipleSelectionAll.length < 2) {
        this.$message.warning('请至少选择两个角色进行合并');
        return;
      }
      this.mergeDialogShow();
    },
    mergeDialogShow() {
      this.$refs['rolesMergeDialogRef'].dialogVisible = true;
    },
    handleRolesMerge(id) {
      const params = {
        mainRoleId: id,
        mergeRoleIds: this.multipleSelectionAll.map(i => i.roleId).filter(i => i !== id).join()
      };
      this.mergeLoading = true;
      mergeRoles(params).then(res => {
        this.mergeLoading = false;
        this.$refs['rolesMergeDialogRef'].handleDialogClose();
        if (res.code === 200) {
          this.$message.success('合并成功');
          this.clearMixinSelection && this.clearMixinSelection();
          this.getList(true);
        }
      }).catch(e => {
        this.mergeLoading = true;
        this.$refs['rolesMergeDialogRef'].handleDialogClose();
      });
    },
    queryClick() {
      this.getList(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.getList(true);
    },
    async getList(reset = false) {
      if (reset) this.page = 1;
      this.listLoading = true;
      roleList(this.page, this.perPage, this.paramsObj).then(({ data }) => {
        if (data.items) {
          data.items.forEach(item => { item._checked = false; });
        }
        this.list = data;
        this.isInit = false;
        this.listLoading = false;
      }, result => {
        this.listLoading = false;
      }).catch(e => {
        console.error(e);
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.getList(true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.getList();
    },
    toEdit(data, copy = false) {
      this.$router.push({
        name: 'authEditRole',
        params: { roleId: data.roleId },
        query: { copy }
      });
    },
    searchOpeartor(item) {
      this.$router.push({
        name: 'operatorManage',
        query: { roleName: item.roleName }
      });
      localStorage.setItem('_roleItem', JSON.stringify({ roleName: item.roleName, roleId: item.roleId, status: item.status }));
    },
    moreOperateChangeStatus(status) {
      return () => this.changeStatus(status);
    },
    // 修改
    changeStatus(status) {
      const selectList = _.cloneDeep(this.multipleSelectionAll);
      if (selectList.length > 0) {
        const ids = selectList.map(item => item.roleId);
        const params = {
          roleIds: ids.join(','),
          status: status
        };
        changeRoleStatus(params).then(res => {
          if (res.code) {
            this.$message({
              type: 'success',
              message: '修改成功'
            });
            this.clearMixinSelection && this.clearMixinSelection();
            this.getList();
          }
        });
      } else {
        this.$message.warning('请先进行选择');
      }
    },
    deleteItem() {
      const selectList = _.cloneDeep(this.multipleSelectionAll);
      const that = this;
      if (selectList.length > 0) {
        this.$confirm('此操作将永久删除这些记录, 是否继续?', '', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          customClass: 'del-message del-message-cancel',
          iconClass: 'del-icon',
          center: true
        }).then(() => {
          const ids = selectList.map(item => item.roleId);
          const params = {
            ids: ids.join(',')
          };
          deleteRole(params).then(res => {
            if (res.code) {
              that.$message({
                type: 'success',
                message: '删除成功'
              });
              this.clearMixinSelection && this.clearMixinSelection();
              that.getList(true);
            }
          });
        });
      } else {
        this.$message.warning('请先进行选择');
      }
    },
    isEditDisabled(roleId) {
      if (hasRouteAuth('auth:operator:adminEdit')) return false;
      if (!hasRouteAuth('auth:operator:edit')) return true;
      if (this.userInfo.userName === '管理员') return false;
      const roleListArr = this.userInfo.roleList || [];
      const ids = roleListArr.map(i => i.roleId);
      return !ids.includes(roleId);
    },
    selectable(row) {
      return !this.isEditDisabled(row.roleId);
    },
    tableRowClassName({ row, rowIndex }) {
      const baseClass = 'pointer';
      if (this.multipleSelectionAll && this.multipleSelectionAll.length > 0) {
        const ids = this.multipleSelectionAll.map(i => i[this.idKey]);
        return ids.includes(row[this.idKey]) ? `table-selected ${baseClass}` : baseClass;
      }
      return baseClass;
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.operator-manage {
  margin: 16px 16px 0px 16px;
  // border:1px solid #eee;
  background-color: #fff;
  padding: 1px 20px 55px 20px;
  .table-list {
    border-radius: 10px;
    .filter {
      margin-top: 16px;
    }
    .u-table {
      font-size: 14px;
    }
    .el-row {
      padding: 0;
    }
  }
  .list-top {
    display: flex;
    align-items: center;
    .list-title {
      flex:1;
    }
    .btn-right{
      display: flex;
      .btn {
        margin-left: 10px;
      }
    }
  }
  .user-status-forbidden {
    color: red;
  }
  .user-status-normal {
    color: green
  }
  .border-left {
    position: relative;
    padding-left:6px;
    margin-left: 6px;
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      margin-top: -7px;
      width: 1px;
      background: #ddd;
      height: 14px;
    }
  }
  .operator-box {
    flex: 1;
    margin-left: 18px;
    display: flex;
    align-items: center;
    .btn-item {
      margin-left: 10px;
      padding: 5px 15px;
      font-size: 13px;
    }
  }
  //& ::v-deep {
  //  th {
  //    .el-checkbox {
  //      display: none;
  //    }
  //  }
  //  .el-pagination__jump {
  //    margin-left: 0 !important;
  //  }
  //}
  .more-btn-group {
    flex:1;
    height: 32px;
    display: flex;
    align-items: center;
  }
}

.link-num {
  color: #406EFF;
  cursor: pointer;
}
.mobile-table {
  & ::v-deep {
    td {
      height: 40px !important;
    }
  }
}
</style>
